package org.dromara.bean.service.impl;

import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.bean.domain.bo.HisPatientBo;
import org.dromara.bean.domain.vo.HisPatientVo;
import org.dromara.bean.domain.HisPatient;
import org.dromara.bean.mapper.HisPatientMapper;
import org.dromara.bean.service.IHisPatientService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 就诊卡Service业务层处理
 *
 * @author Lion Li
 * @date 2024-11-30
 */
@RequiredArgsConstructor
@Service
public class HisPatientServiceImpl implements IHisPatientService {

    private final HisPatientMapper baseMapper;

    /**
     * 查询就诊卡
     *
     * @param id 主键
     * @return 就诊卡
     */
    @Override
    public HisPatientVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询就诊卡列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 就诊卡分页列表
     */
    @Override
    public TableDataInfo<HisPatientVo> queryPageList(HisPatientBo bo, PageQuery pageQuery) {
        Page<HisPatientVo> page = baseMapper.patientList(pageQuery.build(), bo);
        return TableDataInfo.build(page);
    }

    /**
     * 查询符合条件的就诊卡列表
     *
     * @param bo 查询条件
     * @return 就诊卡列表
     */
    @Override
    public List<HisPatientVo> queryList(HisPatientBo bo) {
        LambdaQueryWrapper<HisPatient> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HisPatient> buildQueryWrapper(HisPatientBo bo) {
        LambdaQueryWrapper<HisPatient> lqw = Wrappers.lambdaQuery();
        // 连表查询member表
        lqw.like(StringUtils.isNotBlank(bo.getName()), HisPatient::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), HisPatient::getIdCard, bo.getIdCard());
        lqw.eq(StringUtils.isNotBlank(bo.getMobile()), HisPatient::getMobile, bo.getMobile());
        return lqw;
    }

    /**
     * 新增就诊卡
     *
     * @param bo 就诊卡
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HisPatientBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();

        LambdaQueryWrapper<HisPatient> lqw = new LambdaQueryWrapper<>();
        lqw.eq(HisPatient::getIdCard, bo.getIdCard());
        lqw.eq(HisPatient::getMemberId, loginUser.getUserId());
        Long count = baseMapper.selectCount(lqw);
        if (count > 0) {
            throw new ServiceException("该身份证号已存在");
        }


        HisPatient add = MapstructUtils.convert(bo, HisPatient.class);
        add.setMemberId(loginUser.getUserId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改就诊卡
     *
     * @param bo 就诊卡
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HisPatientBo bo) {
        Long userId = LoginHelper.getUserId();
        HisPatient update = MapstructUtils.convert(bo, HisPatient.class);


        LambdaQueryWrapper<HisPatient> lqw = new LambdaQueryWrapper<>();
        lqw.eq(HisPatient::getIdCard, bo.getIdCard());
        lqw.eq(HisPatient::getMemberId,userId);
        Long count = baseMapper.selectCount(lqw);
        if (count > 1) {
            throw new ServiceException("该身份证号已存在");
        }

        update.setMemberId(userId);
        validEntityBeforeSave(update);
        baseMapper.updateById(update);
        return  true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HisPatient entity){
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (!entity.getMemberId().equals(loginUser.getUserId())){
            throw new ServiceException("操作失败，当前登录用户与就诊卡用户不匹配");
        }

        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除就诊卡信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(isValid){

            LambdaQueryWrapper<HisPatient> hisPatientLambdaQueryWrapper = new LambdaQueryWrapper<>();
            hisPatientLambdaQueryWrapper.in(HisPatient::getId, ids);
            List<HisPatientVo> hisPatientVos = baseMapper.selectVoList(hisPatientLambdaQueryWrapper);
            for (HisPatientVo hisPatientVo : hisPatientVos) {
                if (!hisPatientVo.getMemberId().equals(loginUser.getUserId())){
                    throw new ServiceException("操作失败，当前登录用户与就诊卡用户不匹配");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    //***********************************小程序***********************************
    /**
     * 分页查询就诊卡列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 就诊卡分页列表
     */
    @Override
    public TableDataInfo<HisPatientVo> xcxQueryPageList(HisPatientBo bo, PageQuery pageQuery){
        LoginUser loginUser = LoginHelper.getLoginUser();
        bo.setMemberId(loginUser.getUserId().toString());
        Page<HisPatientVo> page = baseMapper.patientList(pageQuery.build(), bo);
        return TableDataInfo.build(page);
    }
}
